package org.ww.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.ww.common.constant.RabbitMqConstant;
import org.ww.common.to.mq.SeckillOrderTo;
import org.ww.common.utils.R;
import org.ww.common.vo.MemberRespVo;
import org.ww.seckill.feign.CouponFeignService;
import org.ww.seckill.feign.ProductFeignService;
import org.ww.seckill.interceptor.SeckillLoginInterceptor;
import org.ww.seckill.service.SeckillService;
import org.ww.seckill.to.SeckillSkuRedisTo;
import org.ww.seckill.vo.SeckillSessionsWithSkus;
import org.ww.seckill.vo.SkuInfoVo;

import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @program: gmall
 * @description:
 * @author: ww
 * @create: 2024-11-05 14:33
 **/
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public static final String SESSION_CACHE_PREFIX = "seckill:sessions:";
    public static final String SKUKILL_CHACHE_PREFIX = "seckill:skus";

    public static final String SECKILL_STOCK_SEMAPHORE = "seckill:stock:"; //+商品随机码

    /**
     * 上架最近三天的秒杀商品
     */
    @Override
    public void uploadSeckillLatested3Days() {
        R r = couponFeignService.getLates3DaySession();
        if(r.getCode() == 0){
            //上架商品
            List<SeckillSessionsWithSkus> sessionDatas = r.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //缓存活动信息
            saveSessionInfos(sessionDatas);
            //缓存活动关联的商品信息
            saveSessionSkuInfos(sessionDatas);
        }
    }

    public List<SeckillSkuRedisTo> currentSeckillBlockHandler(BlockException e){
        log.error("getCurrentSeckillSkus资源被限流了:"+e.getMessage());
        return null;
    }
    /**
     * 返回当前时间可以秒杀的商品信息
     */
    @SentinelResource(value = "getCurrentSeckillSkus",blockHandler = "currentSeckillBlockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1、获取当前系统时间
        long nowTime = System.currentTimeMillis();
        try(Entry entry = SphU.entry("seckillSkus")){
            //2、判断当前时间属于哪个活动场次
            Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
            for (String key : keys) {
                String sessoinKey = key.replace(SESSION_CACHE_PREFIX, "");
                String[] s = sessoinKey.split("_");
                Long startTime = Long.parseLong(s[0]);
                Long endTime = Long.parseLong(s[1]);
                if(nowTime >= startTime && nowTime <= endTime){
                    //把范围内的所有sku数据取出来
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CHACHE_PREFIX);
                    List<String> skuInfos = ops.multiGet(range);
                    if(CollectionUtils.isNotEmpty(skuInfos)){
                        List<SeckillSkuRedisTo> redisTos = skuInfos.stream()
                                .map(sku -> {
                                    SeckillSkuRedisTo redisTo = JSON.parseObject(sku.toString(), SeckillSkuRedisTo.class);
                                    return redisTo;
                                }).collect(Collectors.toList());
                        return redisTos;
                    }
                }
            }
        }catch (BlockException e){
            log.error("seckillSkus资源被限流了："+e.getMessage());
        }

        //3、将该场次的所有sku数据信息返回
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CHACHE_PREFIX);
        Set<String> keys = ops.keys();
        String regx = "\\d_" + skuId;
        for (String key : keys) {
            //如果匹配的话
            if(Pattern.matches(regx,key)){
                String s = ops.get(key);
                SeckillSkuRedisTo redisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);
                //处理随机码：如果当前商品处于秒杀时间，则将随机码返回
                long currentTime = System.currentTimeMillis();
                Long startTime = redisTo.getStartTime();
                Long endTime = redisTo.getEndTime();
                if(currentTime >= startTime && currentTime <= endTime){

                }else{
                    redisTo.setRandomCode(null);
                }
                return redisTo;
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo memberRespVo = SeckillLoginInterceptor.loginUser.get();

        //获取当前秒杀的商品信息
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CHACHE_PREFIX);
        String s = ops.get(killId);
        if(StringUtils.isNotBlank(s)){
            SeckillSkuRedisTo redisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);
            //1、校验时间的合法性
            Long startTime = redisTo.getStartTime();
            Long endTime = redisTo.getEndTime();
            long nowTime = System.currentTimeMillis();

            long ll = endTime - nowTime;

            if(nowTime >= startTime && nowTime <= endTime){
                //2、校验商品id和验证码是否正确
                String pKillId = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
                if(redisTo.getRandomCode().equals(key) && pKillId.equals(killId)){
                    //3、验证购物数量是否合理和库存量是否充足
                    Integer seckillLimit = redisTo.getSeckillLimit();
                    //获取信号量
                    String seckillCount = redisTemplate.opsForValue().get(SECKILL_STOCK_SEMAPHORE + key);
                    Integer count = Integer.valueOf(seckillCount);
                    //判断信号量是否大于0,并且买的数量不能超过库存
                    if (count > 0 && num <= seckillLimit && count > num ){
                        //4、验证这个人是否已经购买过，幂等性，如果没有购买过就进行占位 userId_sessionId_skuId
                        String absentKey = memberRespVo.getId()+ "_" + pKillId;
                        Boolean isAbsent = redisTemplate.opsForValue().setIfAbsent(absentKey, num.toString(), ll, TimeUnit.MILLISECONDS);
                        if(isAbsent){
                            RSemaphore semaphore = redissonClient.getSemaphore(SECKILL_STOCK_SEMAPHORE + key);
                            //这里不用acquire方法，该方法是阻塞的方式
                            try {
                                boolean b = semaphore.tryAcquire(num,100,TimeUnit.MILLISECONDS);
                                //秒杀成功
                                //快速下单，返回订单号
                                if(b){
                                    String orderId = IdWorker.getTimeId();
                                    SeckillOrderTo orderTo = new SeckillOrderTo();
                                    orderTo.setOrderSn(orderId);
                                    orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                    orderTo.setMemberId(memberRespVo.getId());
                                    orderTo.setNum(num);
                                    orderTo.setSkuId(redisTo.getSkuId());
                                    orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                    //RabbitMqConstant.ORDER_EVENT_EXCHANGE,RabbitMqConstant.ORDER_CREATE_ORDER_BINDING,entity
                                    //发送订单消息队列
                                    rabbitTemplate.convertAndSend(RabbitMqConstant.ORDER_EVENT_EXCHANGE,RabbitMqConstant.ORDER_SECKILL_ORDER_BINDING,orderTo);
                                    return orderId;
                                }
                            } catch (InterruptedException e) {
                                return null;
                            }

                        }
                    }
                }
            }
        }
        return null;
    }

    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessionDatas) {
        sessionDatas.stream().forEach(s -> {
            long startTime = s.getStartTime().getTime();
            long endTime = s.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
            //保存
            List<String> ids = s.getRelationSkus()
                    .stream()
                    .map(r -> r.getPromotionSessionId().toString() + "_" + r.getSkuId().toString())
                    .collect(Collectors.toList());
            if(!redisTemplate.hasKey(key)){
                redisTemplate.opsForList().leftPushAll(key,ids);
            }
        });

    }
    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessionDatas) {
        sessionDatas.stream().forEach(s -> {
            BoundHashOperations<String, Object, Object> skuBoundHash = redisTemplate.boundHashOps(SKUKILL_CHACHE_PREFIX);
            s.getRelationSkus().stream().forEach(relationSku -> {
                if(!skuBoundHash.hasKey(s.getId() + "_" + relationSku.getSkuId())){
                    //缓存商品
                    SeckillSkuRedisTo skuRedisTo = new SeckillSkuRedisTo();
                    //1、sku的基本数据
                    R skuInfo = productFeignService.getSkuInfo(relationSku.getSkuId());
                    if(skuInfo.getCode() == 0){
                        SkuInfoVo skuInfoVo = skuInfo.getData("skuInfo",new TypeReference<SkuInfoVo>() {
                        });
                        skuRedisTo.setSkuInfoVo(skuInfoVo);
                    }

                    //2、sku的秒杀数据
                    BeanUtils.copyProperties(relationSku,skuRedisTo);

                    //3、设置商品的秒杀时间
                    skuRedisTo.setStartTime(s.getStartTime().getTime());
                    skuRedisTo.setEndTime(s.getEndTime().getTime());

                    //4、给商品加上随机码（作用：防止秒杀还未开始，就有恶意攻击持续进行访问，同时也能达到限流的作用）
                    String randomCode = UUID.randomUUID().toString().replace("-", "");
                    skuRedisTo.setRandomCode(randomCode);
                    //5、使用库存作为分布式信号量  限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SECKILL_STOCK_SEMAPHORE + randomCode);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(relationSku.getSeckillCount());

                    String skuRedisToJson = JSON.toJSONString(skuRedisTo);
                    skuBoundHash.put(s.getId() + "_" + relationSku.getSkuId().toString(),skuRedisToJson);
                }
            });
        });
    }


}
